import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Dropdown, Menu, Icon, Popconfirm, message, Modal, Select, Tree, TreeSelect } from 'antd'
import _ from 'lodash'

import Ajax from 'lib/Ajax'
import AreaInput from 'components/areaInput'
import OrgInput from 'components/orgInput'
import { getNewTreeData, findRowData, addRowData, removeRowData, confirmDelete, getNameByCode, validatorArea, validatorOrg } from 'lib/fun'

const ButtonGroup = Button.Group;
const FormItem = Form.Item;
const TreeNode = Tree.TreeNode;
const SelectTreeNode = TreeSelect.TreeNode;

class ModuleName extends Component {
	constructor(props) {
    super(props);
    this.search = {};
    this.state = {
      loading: false,
      visible: false,
      editType: "",
      rowdata: {},
      treeData: [],
      selected: {},
      current: 1,   //当前第几页
      total: 10,   //总共多少页
      pageSize: 10   //每页多少行
    }
  }

  componentDidMount() {
    this.onLoadData();
  }

  componentWillReceiveProps(nextProps){
    var self = this;
    self.setState({
      current: 1
    });
    console.log(nextProps.search, this.props.search);
    if(!_.isEqual(this.props.search, nextProps.search)){
      this.search = nextProps.search;
      self.onLoadData();
    }
  }

  onSelect = (info, e) => {
    console.log(info);
    var selected = findRowData(this.state.treeData, info, 'orgId');

    // this.props.addressChange(selected);
    if(selected){
      this.setState({
        selected
      });
    }

    // e.node.onExpand();
    this.onLoadData(e.node);
  }

  onLoadData = (treeNode) => {
    var self = this;
    console.log('load organization2');
    var selected = findRowData(this.state.treeData, treeNode?treeNode.props.eventKey:0, 'orgId');
    console.log(selected);
    return new Promise((resolve) => {
      if(selected&&selected.children){
        self.setState({
          loading: false
        });
        resolve();
      }else{
        var { orgLevelCode, orgCode, orgName, orgParentCode } = this.search;
        Ajax({
          url: '/organization/list',
          data: {
            orgParentId: treeNode?treeNode.props.eventKey:0,
            // orgLevelCode,
            // orgCode, 
            // orgName, 
            // orgParentCode,
            perPage: 100
          },
          success: function(data){
            var treeData = self.state.treeData;
            if(treeNode&&self.state.treeData.length > 0){
              treeData = getNewTreeData(treeData, treeNode.props.eventKey, data.list||[], 'orgId');
              console.log(treeData);
            }else{
              treeData = data.list
            }
            self.setState({
              loading: false,
              treeData
            });
            resolve();
          },
          error: function(error){
            message.error(error);
          }
        });
      }
    });
  }

  pageOnChange = (page)=>{
    this.setState({
      current: page
    });
  }

  showSizeChange = (current, pageSize)=>{
    var page = Math.ceil(this.state.current*this.state.pageSize/pageSize);
    var pageSize = pageSize;
    var current = page;
    this.setState({
      pageSize,
      current
    });
  }
  // 操作
  operate = (type, row)=>{
    if(type == 'edit'){
      this.setState({
        visible: true,
        editType: 'edit',
        rowdata: row
      });
    }else{
      if(this.state.selected.orgCode){
        this.setState({
          visible: true,
          editType: 'new'
        });
      }else{
        message.error('请先选择机构！');
      }
    }
  }

  editOk = (type, rowdata)=>{
    var self = this;
    if(type == 'edit'){
      var find = findRowData(this.state.treeData, rowdata.orgId, 'orgId');
      if(find){
        if(find.orgParentId != rowdata.orgParentId){
          removeRowData(self.state.treeData, rowdata.orgId);
          addRowData(self.state.treeData, rowdata);
        }else{
          Object.assign(find, {
            orgCode: rowdata.orgCode,
            orgName: rowdata.orgName,
            orgNameZw: rowdata.orgNameZw,
            orgLevelId: rowdata.orgLevelId,
            orgParentId: rowdata.orgParentId,
            orgParentCode: rowdata.orgParentCode,
            orgTypeId: rowdata.orgTypeId,
            remark: rowdata.remark
          });
        }
      }
      self.setState({
        visible: false,
        rowdata: {},
        treeData: self.state.treeData
      });
      message.success('修改记录成功！');
    }else{
      addRowData(self.state.treeData, rowdata);
      self.setState({
        visible: false,
        rowdata: {},
        treeData: self.state.treeData
      });
      message.success('增加记录成功！');
    }
  }
  editCancel = ()=>{
    this.setState({
      visible: false,
      rowdata: {}
    });
  }

  doDelete = (id)=>{
    var self = this;
    confirmDelete(()=>{
      Ajax({
        url: '/organization/delete',
        data: {
          "orgId": id
        },
        success: function(data){
          removeRowData(self.state.treeData, id);
          self.setState({
            treeData: self.state.treeData
          });
        },
        error: function(error){
          message.error(error);
        }
      });
    }, ()=>{
       message.info('取消删除区划');
    });
   
  }
  
  render() {
    var pagination = {
      current: this.state.current,
      total: this.state.total,
      onChange: this.pageOnChange,
      showSizeChanger: true,
      pageSize: this.state.pageSize,
      onShowSizeChange: this.showSizeChange,
      showTotal: total => `总共 ${total} 条`
    };
    // console.log(this.state.selected)
    const { config } = this.props;
    const columns = [{
        title: '机构代码',
        dataIndex: 'orgCode'
      }, {
        title: '机构名称',
        dataIndex: 'orgName'
      }, {
        title: '上级机构名称',
        dataIndex: 'orgParentId',
        render: ()=> <span>{ this.state.selected.orgName }</span>
      }, {
        title: '机构类型',
        dataIndex: 'orgTypeCode',
        render: (text, record) => <span>{ getNameByCode(config, 'orgType', text) }</span>
      }, {
        title: '业务主管部门类型',
        dataIndex: 'businessDeptCode',
        render: (text, record) => <span>{ getNameByCode(config, 'businessDept', text) }</span>
      }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <Dropdown overlay={
              <Menu>
                <Menu.Item>
                  <a onClick={this.operate.bind(this, "edit", record)} href="javascript:;">编辑</a>
                </Menu.Item>
                <Menu.Item>
                  <a href="javascript:;" onClick={this.doDelete.bind(this, record.orgId)}>删除</a>
                </Menu.Item>
              </Menu>
            }>
              <a className="ant-dropdown-link" href="javascript:;">
                操作 <Icon type="down" />
              </a>
            </Dropdown>
          </span>
        )
    }];

    const loop = data => data.map((item) => {
      if (item.children&&item.children.length > 0) {
        return <TreeNode title={item.orgName} key={item.orgId}>{loop(item.children)}</TreeNode>;
      }
      return <TreeNode title={item.orgName} key={item.orgId} isLeaf={item.children&&item.children.length == 0}/>;
    });
    const treeNodes = loop(this.state.treeData);

    const businessDept = this.props.config.businessDept||[];
    const orgType = this.props.config.orgType||[];

    var dataList = this.state.selected.children||this.state.treeData||[];
    var { orgCode, orgName } = this.props.search;
    if(orgCode){
      dataList = _.filter(dataList, _.negate((item)=>{
        return item.orgCode != orgCode
      }))
    }
    if(orgName){
      dataList = _.filter(dataList, _.negate((item)=>{
        return item.orgName != orgName
      }))
    }

    return (
    	<div>
        <Row>
          <Col span={4}>
            <Tree 
              ref="tree"
              autoExpandParent
              onSelect={this.onSelect} 
              loadData={this.onLoadData}
            >
              {treeNodes}
            </Tree>
          </Col>
          <Col span={20}>
            <div className="table-con no-expand">
              <Table
                columns={ columns }
                dataSource={ dataList }
                pagination={ false }
                loading={this.state.loading}
                rowKey="orgId"
                title={() => (<div>
                                <Button type="primary" style={{marginRight: 15}} icon="plus" onClick={ this.operate.bind(this, 'new') }>新建</Button>
                                {/*<Button type="primary" icon="export">批量导入</Button>*/}
                              </div>)}
              />
            </div>
          </Col>
        </Row>
        <EditModule 
          visible={ this.state.visible }
          address={ this.state.selected }
          onOk={ this.editOk }
          onCancel={ this.editCancel }
          type={ this.state.editType }
          rowdata={ this.state.rowdata }
          businessDept={ businessDept }
          orgType={ orgType }
        />
    	</div>
    )
  }
}

module.exports = ModuleName


class Edit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      treeData: [],
      areaTreeData: []
    }
  }

  componentWillReceiveProps(nextProps){
    if(!nextProps.visible){
      this.props.form.resetFields();
    }
    if(nextProps.visible){
      // nextProps.type=='edit'&&this.state.treeData.length <= 0&&this.loadOrg();
      // this.state.areaTreeData.length <= 0&&this.loadArea();
    }
  }

  loadOrg = (treeNode)=>{
    console.log('load organization');
    var self = this;
    var selected = findRowData(this.state.treeData, treeNode?treeNode.props.eventKey:0, 'orgId');
    return new Promise((resolve) => {
      if(selected&&selected.children){
        resolve();
      }else{
        Ajax({
          url: '/organization/list',
          data: {
            orgParentId: treeNode?treeNode.props.eventKey:0,
            perPage: 100
          },
          success: function(data){
            var treeData = self.state.treeData;
            if(treeNode&&self.state.treeData.length > 0){
              treeData = getNewTreeData(treeData, treeNode.props.eventKey, data.list, 'orgId');
            }else{
              treeData = data.list;
            }
            self.setState({
              treeData
            });
            resolve();
          },
          error: function(error){
            message.error(error);
          }
        });
      }
    });
  }

  loadArea = (treeNode)=>{
    console.log('load area');
    var self = this;
    var selected = findRowData(this.state.areaTreeData, treeNode?treeNode.props.eventKey:0, 'areaId');
    return new Promise((resolve) => {
      if(selected&&selected.children){
        resolve();
      }else{
        Ajax({
          url: '/area/list',
          data: {
            areaParentId: treeNode?treeNode.props.eventKey:0,
            perPage: 100
          },
          success: function(data){
            var areaTreeData = self.state.areaTreeData;
            if(treeNode&&self.state.areaTreeData.length > 0){
              areaTreeData = getNewTreeData(areaTreeData, treeNode.props.eventKey, data.list, 'areaId');
            }else{
              areaTreeData = data.list;
            }
            self.setState({
              areaTreeData
            });
            resolve();
          },
          error: function(error){
            message.error(error);
          }
        });
      }
    });
  }

  handleCommit = () => {
    var self = this;
    self.props.form.validateFields((err, values) => {
      if(err == null&&!this.state.loading){
        self.setState({
          loading: true
        });
        const { type, rowdata, address  } = self.props;
        console.log(values);
        if(self.props.type == 'edit'){
          values.orgId = rowdata.orgId;
          values.orgParentId = values.orgParent.orgId;
          values.orgParentCode = values.orgParent.orgCode||rowdata.orgParentCode;
          values.areaId = values.area.areaId;
        }else{
          values.orgParentId = address.orgId;
          values.orgParentCode = address.orgCode;
          values.areaId = values.area.areaId;
        }
        Ajax({
          url: '/organization/save',
          data: values,
          success: function(data){
            self.setState({
              loading: false
            });
            self.props.onOk(self.props.type, data);
          },
          error: function(error){
            self.setState({
              loading: false
            });
            message.error(error);
          }
        });
      }
    });
  }

  onCancel = ()=>{
    this.setState({
      loading: false
    });
    this.props.onCancel();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const { visible, type, rowdata, address, config, businessDept, orgType } = this.props;
    
    console.log(this.state.treeData);
    const loop = data => data.map((item) => {
      if (item.children&&item.children.length > 0) {
        return <SelectTreeNode title={item.orgName} key={item.orgId+""} value={item.orgId + ""}>{loop(item.children)}</SelectTreeNode>;
      }
      console.log('isLeaf',item.children&&item.children.length == 0 );
      return <SelectTreeNode title={item.orgName} key={item.orgId+""} value={item.orgId + ""} isLeaf={item.children&&item.children.length == 0}/>;
    });
    const loop2 = data => data.map((item) => {
      if (item.children&&item.children.length > 0) {
        return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""}>{loop2(item.children)}</SelectTreeNode>;
      }
      console.log('isLeaf',item.children&&item.children.length == 0 );
      return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""} isLeaf={item.children&&item.children.length == 0}/>;
    });
    const treeNodes = loop(this.state.treeData);
    const AeraTreeNodes = loop2(this.state.areaTreeData);
    return (<Modal 
              title={ type == 'edit'?"修改机构":"新建机构" }
              visible={visible}
              onOk={ this.handleCommit } 
              onCancel={ this.onCancel }
              okText="确定" 
              cancelText="取消"
            >
              <Spin spinning={this.state.loading}>
                <Form
                  horizontal
                >
                  <Row gutter={20}>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="机构代码">
                        {getFieldDecorator("orgCode",{
                          initialValue: type == 'edit'?rowdata.orgCode:"",
                          rules: [{
                            required: true, message: '请输入机构代码',
                          }]
                        })(
                          type == 'edit'?<Input disabled/>:<Input />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="机构名称">
                        {getFieldDecorator("orgName",{
                          initialValue: type == 'edit'?rowdata.orgName:"",
                          rules: [{
                            required: true, message: '请输入机构名称',
                          }]
                        })(
                          <Input />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row gutter={20}>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="机构名称(藏)">
                        {getFieldDecorator("orgNameZw",{
                          initialValue: type == 'edit'?rowdata.orgNameZw:"",
                        })(
                          <Input />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="机构类型">
                        {getFieldDecorator("orgTypeCode",{
                          initialValue: type == 'edit'?rowdata.orgTypeCode+"":"",
                          rules: [{
                            required: true, message: '请选择机构类型',
                          }]
                        })(
                          <Select>
                            {
                              orgType.map(function(obj){
                                return (<Select.Option key={obj.dictionaryId} value={ obj.dictionaryCode }>{ obj.dictionaryName }</Select.Option>)
                              })
                            }
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row gutter={20}>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="上级机构">
                        {/*
                        {getFieldDecorator("orgParentId",{
                          initialValue: type == 'edit'?rowdata.orgParentId+"":address.orgName,
                          rules: [{
                            required: true, message: '请选择上级机构',
                          }]
                        })(
                          type == 'edit'?(
                            <TreeSelect
                              allowClear
                              loadData={ this.loadOrg }
                            >
                              { treeNodes }
                            </TreeSelect>
                          ):(
                            <Input disabled/>
                          )
                        )}
                        */}
                        {getFieldDecorator("orgParent",{
                          initialValue: type == 'edit'?{orgId: rowdata.orgParentId+"", orgName: rowdata.orgParentName||rowdata.orgParentId}:{},
                          rules: [{ validator: validatorOrg}],
                        })(
                          <OrgInput />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="行政区划">
                        {/*
                        {getFieldDecorator("areaId",{
                          initialValue: type == 'edit'?rowdata.areaId+"":"",
                          rules: [{
                            required: true, message: '请选择行政区划',
                          }]
                        })(
                            <TreeSelect
                              allowClear
                              loadData={ this.loadArea }
                            >
                              { AeraTreeNodes }
                            </TreeSelect>
                        )}
                        */}
                        {getFieldDecorator("area",{
                          initialValue: type == 'edit'?{areaId: rowdata.areaId+"", areaName: rowdata.areaName||rowdata.areaId}:{},
                          rules: [{ validator: validatorArea}],
                        })(
                          <AreaInput />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row gutter={20}>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="业务主管部门类型">
                        {getFieldDecorator("businessDeptCode",{
                          initialValue: type == 'edit'?rowdata.businessDeptCode+"":"",
                          rules: [{
                            required: true, message: '请选择业务主管部门类型',
                          }]
                        })(
                          <Select>
                            {
                              businessDept.map(function(obj){
                                return (<Select.Option key={obj.dictionaryId} value={ obj.dictionaryCode }>{ obj.dictionaryName }</Select.Option>)
                              })
                            }
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row gutter={20} className="area-modifier">
                    <Col span={24}>
                      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="概述">
                        {getFieldDecorator("remark",{
                          initialValue: type == 'edit'?rowdata.remark:"",
                        })(
                          <Input type="textarea"/>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                </Form>
              </Spin>
            </Modal>);
  }
}
var EditModule = Form.create()(Edit);
